/*
 * Module name : WorkItemForm
 */
import Mn from 'backbone.marionette';
import Radio from 'backbone.radio';
import {
    hideRegion,
    showRegion
} from 'backbone-tools';

import ModalFormBehavior from 'base/behaviors/ModalFormBehavior.js';
import InputWidget from 'widgets/InputWidget.js';
import CheckboxWidget from 'widgets/CheckboxWidget.js';
import TextAreaWidget from 'widgets/TextAreaWidget.js';
import SelectWidget from 'widgets/SelectWidget.js';
import RadioChoiceButtonWidget from 'widgets/RadioChoiceButtonWidget.js';
import TvaProductFormMixin from 'base/views/TvaProductFormMixin.js';
import CatalogComponent from 'common/views/CatalogComponent.js';

const template = require('./templates/WorkItemForm.mustache');

const WorkItemForm = Mn.View.extend(TvaProductFormMixin).extend({
    template: template,
    tagName: 'section',
    id: 'workitem_form',
    partial: false,
    behaviors: [ModalFormBehavior],
    regions: {
        erros: ".errors",
        locked: '.field-locked',
        label: ".field-label",
        type_: '.field-type_',
        description: '.field-description',
        mode: '.field-mode',
        supplier_ht: '.field-supplier_ht',

        ht: '.field-ht',
        quantity: '.field-quantity',
        unity: '.field-unity',
        catalogContainer: "#catalog-container",
        sync_catalog: ".field-sync_catalog"
    },
    ui: {
        unlockButton: 'button.unlock',
        lockContainer: 'div.alert-locked',
        main_tab: "ul.nav-tabs li:first a",
    },
    // event_prefix: "work:item",
    // Listen to the current's view events
    events: {
        'click @ui.unlockButton': 'unlockForm'
    },
    // Listen to child view events
    childViewEvents: {
        'catalog:insert': "onCatalogInsert",
        'mode:change': 'onModeChange',
    },
    // Bubble up child view events
    childViewTriggers: {
        'finish': 'data:modified'
    },
    initialize() {
        if (this.getOption('edit')) {
            // Only partial edit needed
            this.partial = true;
        } else {
            // All model datas will be submitted
            this.partial = false;
        }
        this.config = Radio.channel('config');
        this.unity_options = this.config.request(
            'get:options',
            'unities'
        );
    },
    refreshForm() {
        // All the field are editable if not locked or no base_sale_product_id set
        this.showLocked();
        this.showLabelAndType();
        this.showDescription();
        this.showModeToggle();
        this.renderModeRelatedFields();
        this.showQuantity();
        this.showUnity();
        this.showSyncCatalog();
    },
    getFieldCommonOptions(attribute, base_label) {
        let result = {
            label: base_label,
            field_name: attribute,
            value: this.model.get(attribute)
        };
        if (this.model.isFromCatalog(attribute)) {
            result.label += " hérité(e) du catalogue";
        }
        return result;
    },
    showLocked() {
        this.showChildView(
            'locked',
            new InputWidget({
                type: 'hidden',
                field_name: 'locked',
                value: this.model.get('locked')
            })
        );
    },
    showLabelAndType() {
        if (!this.model.has('base_sale_product_id')) {
            this.showChildView('label', new InputWidget({
                title: "Nom interne du produit (utilisé dans le catalogue)",
                field_name: 'label',
                value: this.model.get('label'),
                description: "Après insertion dans le produit composé courant, ce produit sera également inséré dans votre catalogue produit",
                required: true,
            }));

            let type_options = this.config.request(
                'get:options', 'base_product_types'
            );

            this.showChildView('type_', new SelectWidget({
                title: "Type de produit (utilisé dans le catalogue)",
                field_name: 'type_',
                value: this.model.get('type_'),
                options: type_options,
                label_key: 'label',
                id_key: 'value',
                required: true,
            }));
        } else {
            let view = this.getChildView('label')
            if (view) {
                view.destroy();
                view = this.getChildView('type_');
                if (view) {
                    view.destroy();
                }
                this.$el.find('div.alert-info').hide();
            }
        }
    },
    showDescription() {
        this.showChildView(
            'description',
            new TextAreaWidget({
                label: "Description",
                description: "Description utilisée dans les devis ou factures",
                field_name: 'description',
                value: this.model.get('description'),
                tinymce: true,
                required: true,
            })
        );
    },
    showModeToggle() {
        const options = this.getFieldCommonOptions('mode', 'Mode de calcul des prix');
        options['options'] = [{
                'label': 'HT',
                'value': 'ht'
            },
            {
                'label': "Coût d'achat",
                'value': 'supplier_ht'
            },
        ];
        options["finishEventName"] = "mode:change";
        const view = new RadioChoiceButtonWidget(options);
        this.showChildView(
            "mode",
            view
        )
    },
    renderModeRelatedFields() {
        this.showSupplierHt();
        this.showHt();
    },
    showSupplierHt() {
        const region = this.getRegion('supplier_ht');
        if (this.model.get('mode') == 'supplier_ht') {
            let options = this.getFieldCommonOptions('supplier_ht', "Coût unitaire HT");
            let view = new InputWidget(options);
            this.showChildView('supplier_ht', view);
            showRegion(region);
        } else {
            hideRegion(region);
        }
    },
    showHt(editable) {
        const region = this.getRegion('ht');

        if (this.model.get('mode') == 'ht') {
            let options = this.getFieldCommonOptions('ht', 'Montant unitaire HT');
            let view = new InputWidget(options);
            this.showChildView('ht', view);
            showRegion(region);
        } else {
            hideRegion(region);
        }
    },
    showQuantity() {
        this.showChildView(
            'quantity',
            new InputWidget({
                label: "Quantité par unité d'ouvrage",
                field_name: "quantity",
                value: this.model.get('quantity')
            })
        );
    },
    showUnity() {
        let options = this.getFieldCommonOptions('unity', "Unité");

        options['options'] = this.unity_options;
        options['placeholder'] = 'Choisir une unité';

        let view = new SelectWidget(options);
        this.showChildView('unity', view);
    },
    showSyncCatalog(open_form) {
        if (this.model.get('base_sale_product_id') && !this.model.get('locked')) {
            this.showChildView(
                'sync_catalog',
                new CheckboxWidget({
                    label: "Synchroniser avec le catalogue",
                    description: "Appliquer les modifications ci-dessus au produit " + this.model.get('label') + " du catalogue",
                    field_name: "sync_catalog",
                    value: false,
                    true_val: true,
                    false_val: false,
                })
            )
        }
    },
    templateContext() {
        let title = "Ajouter un produit à ce produit composé"
        let raw_create = false;
        let help_text = "";

        if (this.getOption('edit')) {
            title = "Modifier le produit " + this.model.get('label') + " de ce produit composé";
        }
        if (!this.model.get('base_sale_product_id')) {
            help_text = "Lorsque vous ajoutez une entrée directement dans ce produit composé, un produit correspondant sera également créé dans le catalogue";
            raw_create = true;
        }
        return {
            title: title,
            help_text: help_text,
            raw_create: raw_create,
            add: !this.getOption('edit'),
        };
    },
    onRender() {
        this.refreshForm();
        if (!this.getOption('edit')) {
            const view = new CatalogComponent({
                query_params: {
                    type_: 'product'
                },
                collection_name: 'catalog_tree',
                multiple: true,
                url: AppOption['catalog_tree_url'],
            });
            this.showChildView('catalogContainer', view);
        }
    },
    unlockForm() {
        this.model.set('locked', false);
        this.ui.lockContainer.hide();
        this.refreshForm();
    },
    onModeChange(key, value) {
        this.model.set(key, value);
        this.renderModeRelatedFields();
    },
    onAttach() {
        this.getUI('main_tab').tab('show');
    },
    onCatalogInsert(sale_products) {
        const collection = this.getOption("destCollection");
        let req = collection.load_from_catalog(sale_products);
        req.then(() => {
            collection._parent.fetch();
            this.triggerMethod('modal:close')
        });
    },
});
export default WorkItemForm;
